package com.lovi.net_.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 建立socket对象连接本机的9999端口
 */
public class SocketTCPClient02 {
    public static void main(String[] args) throws IOException {
        //IP地址,测试为本机ip地址
        InetAddress localHost = InetAddress.getLocalHost();
        Socket socket = new Socket(localHost, 9999);
        System.out.println("客户端socket就绪！");
        //准备发消息给服务器端！！
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("客户端：你好，我是客户端！".getBytes());
        socket.shutdownOutput();//设置结束标记
        //客户端需要接受服务器端发送的消息
        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(b))!=-1){
            System.out.println(new String(b,0,readLen));
        }
        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端退出！");
    }
}
